<template>
  <!-- 使用 v-if 和 v-else 进行条件渲染 -->
  <view class="u-skeleton u-skeleton-fille">
	  <view v-if="account_data.balance"  @click="set_balance_model_show">
	    ¥{{ account_data.balance }}
	  </view>
	  <u-skeleton v-else :loading="skeleton_loading" :animation="true" bgColor="#FFF"></u-skeleton>
	  
	  <u-popup mode="center" border-radius="30"  v-model="set_balance_model">
	    <view style="padding: 30rpx;">
			<u-form :model="set_balance_form" ref="set_balance_uFormRef">
			  <u-form-item label="最新余额"><u-input v-model="set_balance_form.balance" /></u-form-item>
			  <u-button type="success" size="medium" :loading="show_loading" @click="set_balance">确定</u-button>
			</u-form>
		</view>
	  </u-popup>
	  <u-toast ref="uToastRef" />
  </view>

</template>

<script setup>
import { ref, defineEmits  } from 'vue'; 
import {
  updateAccount,
} from '@/static/apis/wzry';

const account_data = defineProps({
  balance: {
    type: String,
    default: '' // 提供一个默认值，防止为 undefined
  },
  account_id: {
	  type: String,
  }
});



const set_balance_form = ref({
  balance: account_data.balance || '' ,// 初始化时使用 prop 的值
});
const uToastRef = ref()

const skeleton_loading = ref(true); // 这个 ref 现在可能不需要了
const show_loading = ref(false);
const set_balance_uFormRef = ref();
const set_balance_model = ref(false);

function set_balance_model_show() {
  set_balance_model.value = true;
}

const emit = defineEmits(['balance-updated']);

function set_balance() {
	set_balance_form.value.account_id = account_data.account_id
	if(set_balance_form.value.account_id == undefined || set_balance_form.value.account_id == '') {
		uToastRef.value.show({
			title: "账号ID错误",
			type: 'error',
		})
	}
  show_loading.value = true;
  updateAccount({
    balance: set_balance_form.value.balance,
	account_id: set_balance_form.value.account_id
  }).then(res => {
    // 更新成功后，可以发出事件通知父组件刷新数据
    // 例如：emit('balance-updated', set_balance_form.value.balance);
	uToastRef.value.show({
		title: res.message,
		type: 'success',
	});
	emit('balance-updated', set_balance_form.value.balance);
  }).catch(err => {
	uToastRef.value.show({
		title: err.message,
		type: 'error',
	})
    console.error(err);
  }).finally(() => {
    show_loading.value = false;
    set_balance_model.value = false;
  });
}
</script>

<style scoped lang="scss">

</style>